package com.radiation.rms.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.radiation.rms.common.R;
import com.radiation.rms.common.RMSCommon;
import com.radiation.rms.common.RMSConstant;
import com.radiation.rms.entity.Area;
import com.radiation.rms.entity.Device;
import com.radiation.rms.mapper.DeviceMapper;
import com.radiation.rms.service.AreaService;
import com.radiation.rms.service.DeviceService;
import com.radiation.rms.vo.AreaVo;
import com.radiation.rms.vo.ConditionVo;
import com.radiation.rms.vo.CountVo;
import com.radiation.rms.vo.DeviceVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 设备表 服务实现类
 * </p>
 *
 * @author 1062
 * @since 2021-04-02
 */
@Service
@Slf4j
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> implements DeviceService {

    @Autowired
    private RMSCommon rmsCommon;

    @Autowired
    private AreaService areaService;

    @Override
    public List<AreaVo> getDataMap(List<String> departmentIds) {
        if (departmentIds == null || departmentIds.size() == 0) {
            return new ArrayList<AreaVo>();
        }
        return this.baseMapper.getDataMap(departmentIds);
    }

    @Override
    public CountVo getCount(List<String> departmentIds) {
        if (departmentIds == null || departmentIds.size() == 0) {
            return new CountVo();
        }
        return this.baseMapper.getCount(departmentIds);
    }

    @Override
    public Map<String, Double[]> getAreaMap(List<String> departmentIds) {
        if (departmentIds == null || departmentIds.size() == 0) {
            return new HashMap<>();
        }
        List<Area> areas = this.baseMapper.getAreaMap(departmentIds);
        return areas.stream().collect(Collectors.toMap(Area::getName, area -> {
            return new Double[]{area.getLongitude(), area.getLatitude()};
        }));
    }

    @Override
    public R queryDevice(DeviceVo deviceVo) {
        String username = SecurityContextHolder.getContext().getAuthentication().getName();
        List<String> departmentIds = rmsCommon.getDepartmentIds(username);
        PageHelper.startPage(deviceVo.getCurrentPage(), deviceVo.getPageSize());
        // TODO 数据控制 与department去交集 list1.retainAll(list2);
        List<String> departments = new ArrayList<>();
        if (StringUtils.isNotBlank(deviceVo.getDepartmentId())) {
            departments.add(deviceVo.getDepartmentId());
            departmentIds.retainAll(departments);
        } else if (StringUtils.isNotBlank(deviceVo.getHospitalId())) {
            departments = areaService.getThreeDepartment(deviceVo.getHospitalId());
            departmentIds.retainAll(departments);
        } else if (StringUtils.isNotBlank(deviceVo.getAreaId())) {
            departments = areaService.getTwoDepartment(deviceVo.getAreaId());
            departmentIds.retainAll(departments);
        } else if (StringUtils.isNotBlank(deviceVo.getCityId())) {
            departments = areaService.getOneDepartment(deviceVo.getCityId());
            departmentIds.retainAll(departments);
        }
        if (departmentIds.size() == 0) {
            return R.error().message(RMSConstant.PERMISSION_DENIED);
        }
        deviceVo.setDepartments(departmentIds);
        List<Device> devices = this.baseMapper.queryDevice(deviceVo);
        List<Device> collect = devices.stream().peek(device -> {
            String path = areaService.getPath(device.getDepartmentId());
            device.setAreaName(path);
        }).collect(Collectors.toList());
        PageInfo<Device> devicePageInfo = new PageInfo<>(devices);
        return R.ok().data("items", devices).data("total", devicePageInfo.getTotal());
    }

    @Override
    public R saveDevice(Device device) {
        this.baseMapper.insert(device);
        return R.ok();
    }

    @Override
    public R getDeviceById(String deviceId) {
        Device device = this.baseMapper.selectById(deviceId);
        List<String> parent = areaService.getParent(device.getDepartmentId());
        device.setDepartmentPath(parent);
        return R.ok().data("item", device);
    }

    @Override
    public R updateDevice(Device device) {
        this.baseMapper.updateById(device);
        return R.ok();
    }

    @Override
    public R initMac() {
        String username = SecurityContextHolder.getContext().getAuthentication().getName();
        List<String> departmentIds = rmsCommon.getDepartmentIds(username);
        List<Device> devices = this.baseMapper.selectList(new QueryWrapper<Device>().in("department_id", departmentIds).select("id,mac,department_id"));
        return R.ok().data("items", devices);
    }

    @Override
    public R deviceCondition(DeviceVo deviceVo) {
        String username = SecurityContextHolder.getContext().getAuthentication().getName();
        List<String> departmentIds = rmsCommon.getDepartmentIds(username);
        PageHelper.startPage(deviceVo.getCurrentPage(), deviceVo.getPageSize());
        List<String> departments = new ArrayList<>();
        if (StringUtils.isNotBlank(deviceVo.getHospitalId())) {
            departments = areaService.getThreeDepartment(deviceVo.getHospitalId());
            departmentIds.retainAll(departments);
        }
        if (departmentIds.size() == 0) {
            return R.error().message(RMSConstant.PERMISSION_DENIED);
        }
        deviceVo.setDepartments(departmentIds);
        List<AreaVo> areaVos = this.baseMapper.deviceCondition(deviceVo);
        List<AreaVo> collect = areaVos.stream().peek(areaVo -> {
           List<ConditionVo> conditionVos =  areaService.getConditionStatus(areaVo.getHospitalId());
            areaVo.setConditionVos(conditionVos);
        }).collect(Collectors.toList());
        PageInfo<AreaVo> devicePageInfo = new PageInfo<>(areaVos);
        return R.ok().data("items", areaVos).data("total", devicePageInfo.getTotal());
    }

    @Override
    public List<Device> getMac(List<String> departmentIds) {
        return baseMapper.getMacData(departmentIds);
    }
}
